// src/pages/bluetoothTest/index.tsx
import { useState, useEffect } from 'react'
import { View, Button, Text, ScrollView, Input, Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Bluetooth, ConnectionState, EmitEvent } from '../../utils/bluetooth'
import './index.css'

// 预设的服务和特征UUID（根据实际设备修改）
const PRESET_UUIDS = {
  services: [
    { name: 'Remote Control', value: '00001812-0000-1000-8000-00805F9B34FB' },
    { name: 'Device Info', value: '0000180A-0000-1000-8000-00805F9B34FB' }
  ],
  characteristics: [
    { name: 'Command', value: '00002A4D-0000-1000-8000-00805F9B34FB' },
    { name: 'Notify', value: '00002A4E-0000-1000-8000-00805F9B34FB' }
  ]
}

export default function BluetoothTest() {
  const [bluetooth] = useState(new Bluetooth({
    deviceNameFilter: /.*/,
    rssiThreshold: -80,
    splitterOptions: {
      crcAlgorithm: 'CRC16_CCITT',
      chunkSize: 512
    }
  }))
  const [devices, setDevices] = useState<any[]>([])
  const [logs, setLogs] = useState<string[]>([])
  const [connectionState, setConnectionState] = useState<ConnectionState>(ConnectionState.DISCONNECTED)
  const [currentDevice, setCurrentDevice] = useState<any>(null)
  const [services, setServices] = useState<any[]>([])
  const [characteristics, setCharacteristics] = useState<any[]>([])
  const [inputData, setInputData] = useState('')
  const [selectedService, setSelectedService] = useState('')
  const [selectedChar, setSelectedChar] = useState('')
  const [receivedData, setReceivedData] = useState<string[]>([])

  // 初始化
  useEffect(() => {
    initBluetooth()
    setupEventListeners()

    return () => {
      bluetooth.disconnect()
      bluetooth.abortScan()
    }
  }, [])

  // 初始化蓝牙
  const initBluetooth = async () => {
    try {
      addLog('初始化蓝牙适配器...')
      await bluetooth.init()
      addLog('蓝牙适配器初始化成功')
    } catch (err) {
      addLog(`初始化失败: ${err.message}`)
    }
  }

  // 设置事件监听
  const setupEventListeners = () => {
    bluetooth.on(EmitEvent.deviceFound, (device) => {
      addLog(`发现设备: ${device.name || '未知'} (${device.deviceId})`)
      setDevices(prev => [...prev, device])
    })

    bluetooth.on(EmitEvent.connectionStateChange, ({ deviceId, connected }) => {
      const status = connected ? '已连接' : '已断开'
      addLog(`设备 ${deviceId} ${status}`)
      setConnectionState(connected ? ConnectionState.CONNECTED : ConnectionState.DISCONNECTED)

      if (!connected) {
        setCurrentDevice(null)
        setServices([])
        setCharacteristics([])
      }
    })

    bluetooth.on(EmitEvent.data, ({ value }) => {
      const dataStr = arrayBufferToHexString(value)
      addLog(`收到数据: ${dataStr}`)
      setReceivedData(prev => [...prev, dataStr])
    })

    bluetooth.on(EmitEvent.fullData, (data) => {
      const fullDataStr = arrayBufferToHexString(data)
      addLog(`收到完整数据包: ${fullDataStr}`)
    })
  }

  // 扫描设备
  const scanDevices = async () => {
    try {
      addLog('开始扫描设备...')
      setDevices([])
      await bluetooth.scanDevices({ timeout: 5000 })
      addLog('扫描完成')
    } catch (err) {
      addLog(`扫描失败: ${err.message}`)
    }
  }

  // 连接设备
  const connectDevice = async (device) => {
    try {
      addLog(`正在连接 ${device.name || device.deviceId}...`)
      setCurrentDevice(device)
      await bluetooth.connect(device.deviceId)

      // 获取服务
      const state = bluetooth.getState()
      setServices(state.services)
      addLog(`发现 ${state.services.length} 个服务`)
    } catch (err) {
      addLog(`连接失败: ${err.message}`)
    }
  }

  // 断开连接
  const disconnectDevice = async () => {
    try {
      addLog('正在断开连接...')
      await bluetooth.disconnect()
      addLog('已断开连接')
    } catch (err) {
      addLog(`断开连接失败: ${err.message}`)
    }
  }

  // 发现特征值
  const discoverCharacteristics = async (serviceId: string) => {
    try {
      addLog(`正在发现服务 ${serviceId} 的特征值...`)
      const chars = await bluetooth.discoverCharacteristics(serviceId)
      setCharacteristics(chars || [])
      addLog(`发现 ${chars?.length || 0} 个特征值`)
    } catch (err) {
      addLog(`发现特征值失败: ${err.message}`)
    }
  }

  // 启用通知
  const startNotification = async (serviceId: string, characteristicId: string) => {
    try {
      addLog(`正在启用通知: ${serviceId} / ${characteristicId}`)
      await bluetooth.startNotification(serviceId, characteristicId)
      addLog('通知已启用')
    } catch (err) {
      addLog(`启用通知失败: ${err.message}`)
    }
  }

  // 发送数据
  const sendData = async () => {
    if (!inputData.trim()) return

    try {
      addLog(`发送数据: ${inputData}`)
      const buffer = stringToArrayBuffer(inputData)
      await bluetooth.write(
        selectedService || services[0]?.uuid,
        selectedChar || characteristics[0]?.uuid,
        buffer,
        { crc: true }
      )
      addLog('数据发送成功')
    } catch (err) {
      addLog(`发送失败: ${err.message}`)
    }
  }

  // 发送大文件测试
  const sendLargeData = async () => {
    try {
      addLog('准备发送大文件数据...')
      // 生成1KB测试数据
      const largeData = new Uint8Array(1024).fill(0xAA).buffer
      await bluetooth.sendLargeData(
        selectedService || services[0]?.uuid,
        selectedChar || characteristics[0]?.uuid,
        largeData
      )
      addLog('大文件数据发送完成')
    } catch (err) {
      addLog(`大文件发送失败: ${err.message}`)
    }
  }

  // 工具函数
  const addLog = (log: string) => {
    setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${log}`])
  }

  const arrayBufferToHexString = (buffer: ArrayBuffer) => {
    return Array.from(new Uint8Array(buffer))
      .map(b => b.toString(16).padStart(2, '0'))
      .join(' ')
  }

  const stringToArrayBuffer = (str: string) => {
    const buffer = new ArrayBuffer(str.length)
    const view = new Uint8Array(buffer)
    for (let i = 0; i < str.length; i++) {
      view[i] = str.charCodeAt(i)
    }
    return buffer
  }

  return (
    <View className='bluetooth-test'>
      <View className='section'>
        <Text className='title'>蓝牙测试工具</Text>
        <Text>状态: {ConnectionState[connectionState]}</Text>
      </View>

      <View className='section'>
        <Button onClick={scanDevices} disabled={connectionState !== ConnectionState.DISCONNECTED}>
          扫描设备
        </Button>

        {devices.length > 0 && (
          <View className='device-list'>
            <Text>发现设备 ({devices.length}):</Text>
            {devices.map(device => (
              <View key={device.deviceId} className='device-item'>
                <Text>{device.name || '未知设备'} ({device.deviceId})</Text>
                <Button
                  size='mini'
                  onClick={() => connectDevice(device)}
                  disabled={connectionState !== ConnectionState.DISCONNECTED}
                >
                  连接
                </Button>
              </View>
            ))}
          </View>
        )}
      </View>

      {connectionState === ConnectionState.CONNECTED && (
        <>
          <View className='section'>
            <Text>已连接设备: {currentDevice?.name || currentDevice?.deviceId}</Text>
            <Button onClick={disconnectDevice}>断开连接</Button>
          </View>

          <View className='section'>
            <Text>服务列表 ({services.length}):</Text>
            <Picker
              mode='selector'
              range={services}
              rangeKey='uuid'
              onChange={(e) => {
                const service = services[e.detail.value]
                setSelectedService(service.uuid)
                discoverCharacteristics(service.uuid)
              }}
            >
              <View className='picker'>
                {selectedService || '选择服务'}
              </View>
            </Picker>

            {characteristics.length > 0 && (
              <>
                <Text>特征值列表 ({characteristics.length}):</Text>
                <Picker
                  mode='selector'
                  range={characteristics}
                  rangeKey='uuid'
                  onChange={(e) => {
                    const char = characteristics[e.detail.value]
                    setSelectedChar(char.uuid)
                  }}
                >
                  <View className='picker'>
                    {selectedChar || '选择特征值'}
                  </View>
                </Picker>

                <Button
                  onClick={() => startNotification(selectedService, selectedChar)}
                  disabled={!selectedService || !selectedChar}
                >
                  启用通知
                </Button>
              </>
            )}
          </View>

          <View className='section'>
            <Input
              value={inputData}
              onInput={(e) => setInputData(e.detail.value)}
              placeholder='输入要发送的数据'
            />
            <View className='button-group'>
              <Button onClick={sendData} disabled={!inputData.trim()}>
                发送数据
              </Button>
              <Button onClick={sendLargeData}>
                发送大文件测试
              </Button>
            </View>
          </View>

          <View className='section'>
            <Text>接收到的数据:</Text>
            <ScrollView scrollY className='data-box'>
              {receivedData.map((data, i) => (
                <Text key={i}>{data}</Text>
              ))}
            </ScrollView>
          </View>
        </>
      )}

      <View className='section'>
        <Text>操作日志:</Text>
        <ScrollView scrollY className='log-box'>
          {logs.map((log, i) => (
            <Text key={i}>{log}</Text>
          ))}
        </ScrollView>
      </View>
    </View>
  )
}
